from webutils.layers.services import ManagerProxy
from message_broker.services import UserService
from message_broker.websocket import User, Device

from .. import const, managers


class UserService(UserService):
    nds_api = ManagerProxy(managers.NDSAPI)
    account_api = ManagerProxy(managers.AccountAPI)

    async def get_user_info(self, token):
        raw_info = await self.account_api.get_user_info(token)
        if not raw_info:
            return None, None
        if 'uid' in raw_info:
            user_info = User(
                id=raw_info['uid'],
                name=raw_info['name'],
                role=None,
            )
            return const.SessionType.USER, user_info
        else:
            if raw_info.get('classroom_id') and raw_info.get('device_type'):
                device_info = Device(
                    id=raw_info['client_id'],
                    classroom_id=raw_info['classroom_id'],
                    name=raw_info['name'],
                    type=const.DeviceType(raw_info['device_type']),
                )
                return const.SessionType.DEVICE, device_info
            else:
                return const.SessionType.DEVICE, 'device_error'

    async def get_user_role(self, token, unit_info, user_id):
        if unit_info.type is const.UnitType.COURSE:
            identity = await self.nds_api.get_user_role_of_course(
                token, unit_info.course_id, user_id)
        else:
            identity = await self.nds_api.get_user_role_of_unit(
                token, unit_info.id, user_id)
        if str(identity) == '1':
            return const.UserRole.TEACHER
        elif str(identity) == '2':
            return const.UserRole.STUDENT
        return const.UserRole.GUEST
